package com.corey.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.corey.model.SimpleSerList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Json {

//	private SimpleSerList _user;// single Parse use

	// create array-json
	public String convertToJson(List<SimpleSerList> users) {
		if (users == null) {
			return null;
		}
		String json = null;
		Iterator<SimpleSerList> iterator = users.iterator();
		json = "[";
		while (iterator.hasNext()) {
			json = json + userToJson(iterator.next());
			if (iterator.hasNext()) {
				json = json + ",";
			}
		}

		json = json + "]";
		System.out.println(json);
		return json;
	}

	// create a single user-json
	// example { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa"
	// }
	public String userToJson(SimpleSerList user) {
		String json = null;
		json = "{\"" + "serListNo" + "\":\"" + user.getSerListNo() + "\"," + "\"" + "serListName"
				+ "\":\"" + user.getSerListName() + "\"," + "\"" + "serListAddr" + "\":\""
				+ user.getSerListAddr() + "\"}";
		return json;
	}

	// Json To LinkedList<User>
	public Iterator<SimpleSerList> parseUserFromJson(String jsonData) {

		Type listType = new TypeToken<LinkedList<SimpleSerList>>() {
		}.getType();
		Gson gson = new Gson();
		LinkedList<SimpleSerList> users = gson.fromJson(jsonData, listType);
		Iterator<SimpleSerList> iterator = users.iterator();
		return iterator;
	}
}
